import os
import json
import requests

def call_api(instruction_content, max_retries=3):
    url = "http://10.119.130.188:8000/v1/chat/completions"
    #url = "http://10.119.130.185:6006/v1/chat/completions"
    for attempt in range(max_retries):
        try:
            payload = {
                "model": "string",
                "messages": [
                    {"role": "user", "content": instruction_content}
                ],
                "do_sample": True,
                "temperature": 0.7,
                "top_p": 0.7,
                "n": 1,
                "max_tokens": 1024,
                "stream": False
            }

            response = requests.post(url, json=payload)

            if response.status_code == 200:
                return response.json()['choices'][0]['message']['content']
            else:
                print(
                    f"API调用失败，重试 {attempt + 1}/{max_retries}，状态码: {response.status_code}, 响应: {response.text}")

            # 根据不同尝试次数进行截取操作
            if attempt == 0:
                cutoff_length = 1700
            elif attempt == 1:
                cutoff_length = 1600
            else:
                cutoff_length = 1200

            index = instruction_content[cutoff_length:].find('。')
            if index != -1:
                instruction_content = instruction_content[:cutoff_length + index + 1]
            else:
                instruction_content = instruction_content

        except requests.RequestException as e:
            print(f"请求异常，重试 {attempt + 1}/{max_retries}，异常信息: {e}")

    return "Error"

def call_api_my(instruction_content, max_retries=2):
    #url = "http://10.119.130.188:8000/v1/chat/completions"
    url = "http://10.119.130.188:6006"
    for attempt in range(max_retries):
        try:
            payload = {
                "prompt": instruction_content
            }

            response = requests.post(url, json=payload)

            if response.status_code == 200:
                return response.json()['response']
            else:
                print(
                    f"API调用失败，重试 {attempt + 1}/{max_retries}，状态码: {response.status_code}, 响应: {response.text}")

            # 根据不同尝试次数进行截取操作
            if attempt == 0:
                cutoff_length = 1700
            elif attempt == 1:
                cutoff_length = 1600
            else:
                cutoff_length = 1200

            index = instruction_content[cutoff_length:].find('。')
            if index != -1:
                instruction_content = instruction_content[:cutoff_length + index + 1]
            else:
                instruction_content = instruction_content

        except requests.RequestException as e:
            print(f"请求异常，重试 {attempt + 1}/{max_retries}，异常信息: {e}")

    return "Error"

if __name__ == '__main__':
    instruction = "你是通义千问吗"

    print(call_api_my(instruction))
def process_files(prompt_file, input_text_file, output_json_file):
    with open(input_text_file, 'r', encoding='utf-8') as file:
        ocr_text = file.read().strip()

    with open(prompt_file, 'r', encoding='utf-8') as file:
        prompt = file.read().strip()

    results = []
    for line in ocr_text.split('\n'):
        instruction = prompt + line.strip()
        if instruction:
            predicted_label = call_api(instruction)
            result = {
                "context": line,
                "predicted_label": predicted_label
            }
            results.append(result)
            print(f"处理完成: 预测标签: {predicted_label}")

    with open(output_json_file, 'w', encoding='utf-8') as outfile:
        json.dump(results, outfile, ensure_ascii=False, indent=4)


